class Solution:
    def evalRPN(self, tokens: list) -> int:
        i = 0
        while len(tokens) > 1:
            if tokens[i] in {"+", "-", "*", "/"}:
                fuhao = tokens.pop(i)
                num_after = tokens.pop(i-1)
                num_before = tokens.pop(i-2)
                mid_res = int(eval(num_before + fuhao + num_after))
                tokens.insert(i-2, str(mid_res))
                i -= 1
            else:
                i += 1
        return tokens[0]


class Solution2:
    def evalRPN(self, tokens: list) -> int:
        zhan = []
        for i in range(len(tokens)):
            try:
                num = int(tokens[i])
                zhan.append(num)
            except:
                fuhao = tokens[i]
                num_after = zhan.pop(-1)
                num_before = zhan.pop(-1)
                if fuhao == "+":
                    mid_res = num_before + num_after
                elif fuhao == "-":
                    mid_res = num_before - num_after
                elif fuhao == "*":
                    mid_res = num_before * num_after
                else:
                    mid_res = int(num_before / num_after)
                zhan.append(mid_res)
        return zhan[0]


a = Solution2()
print(a.evalRPN(["2", "1", "+", "3", "*"]))  # 9
print(a.evalRPN(["4", "13", "5", "/", "+"]))  # 6
print(a.evalRPN(["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"]))  # 22
print(a.evalRPN(["5"]))  # 5
